/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.anniversary.repository;

import me.zhengjie.modules.anniversary.domain.StudentTeacherStatistic;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Zheng Jie
 * @date 2018-11-24
 */
@Repository
public interface StudentTeacherStatisticRepository extends JpaRepository<StudentTeacherStatistic, Long>, JpaSpecificationExecutor<StudentTeacherStatistic> {

    @Query(value = "SELECT t1.time, t1.count AS student_count, ifnull(t2.count,0) AS teacher_count FROM" +
            " (SELECT DATE_FORMAT(create_time, \"%Y-%m-%d\") as time, COUNT(1) as count FROM v_teacher_student_verify_info WHERE user_type=0 GROUP BY DATE_FORMAT(create_time, \"%Y-%m-%d\") ORDER BY time DESC LIMIT :num) AS t1 LEFT JOIN " +
            " (SELECT DATE_FORMAT(create_time, \"%Y-%m-%d\") as time, COUNT(1) as count FROM v_teacher_student_verify_info WHERE user_type=1 GROUP BY DATE_FORMAT(create_time, \"%Y-%m-%d\") ORDER BY time DESC LIMIT :num) AS t2" +
            " ON t1.time = t2.time", nativeQuery = true)
    List<StudentTeacherStatistic> statistics(@Param("num") Integer num);
}
